package com.biubiushop.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author chenjia
 * 根据时间戳与用户id生成token
 */
public class TokenUtil {

    public static String createUserToken(String userId) {
        if (StrUtil.isEmpty(userId)) {
            return null;
        }
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String unEncodeStr = userId + DateUtil.now();
        md.update(unEncodeStr.getBytes());
        byte[] encodedPassword = md.digest();
        StringBuilder buf = new StringBuilder();
        for (byte x : encodedPassword) {
            if ((x & 0xFF) < 16) {
                buf.append("0");
            }
            buf.append(Long.toString(x & 0xFF, 16));
        }
        return buf.toString();
    }


}
